package com.sy.service.impl;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sy.PageVO;
import com.sy.dto.UsersPageDTO;
import com.sy.mapper.UsersMapper;
import com.sy.pojo.Users;
import com.sy.service.UsersService;
import com.sy.utils.BCryptUtils;
import com.sy.utils.StringRandom;
import com.sy.vo.UsersPageVO;
import jakarta.annotation.Resource;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @className: UsersServiceImpl
 * @author: Mr.Liu
 * @date: 2025/10/29 13:57
 * @Version: 1.0
 * @description:
 */
@ConfigurationProperties(prefix = "jwt")
@Service
@Data
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {
//    private static ThreadLocal threadLocal = new ThreadLocal();
    private String secret; //jwt的密钥
    @Resource
    private RedisTemplate<Object,Object> redisTemplate;
    @Resource
    private UsersMapper usersMapper;
    @Override
    public PageVO<UsersPageVO> queryPage(UsersPageDTO usersPageDTO) {
        //定义分页规范
        PageHelper.startPage(usersPageDTO.getCurPage(), usersPageDTO.getPageSize());
        //开始查询
        List<UsersPageVO> usersPageVOList = usersMapper.queryPage(usersPageDTO.getKeyword(), usersPageDTO.getStatus());
        //定义pageInfo对象
        PageInfo<UsersPageVO> pageInfo = new PageInfo<>(usersPageVOList);
        //封装pageVO
        PageVO<UsersPageVO> pageVO = new PageVO<>();
        pageVO.setCurPage(pageInfo.getPageNum());
        pageVO.setPageSize(pageInfo.getPageSize());
        pageVO.setTotal(pageInfo.getTotal());
        pageVO.setDataList(pageInfo.getList());
        return pageVO;
    }

    @Override
    public boolean updateStatus(Integer id, Integer status) {

        return usersMapper.updateStatus(id,status)>0;
    }

    @Override
    public String userLogin(String phone, String code) {
        //获取redis中的手机号
        String redisCode = (String)redisTemplate.opsForHash().get("code", phone);
        if(StringUtils.hasText(redisCode)){
            //手机号有对应的验证码->redis中和页面上你自己写的验证码对比
            if (redisCode.equals(code)) {
                //将手机号保存到数据库中(随机账号和密码)--->用户id--->主键回填-->获取用户id
                Users users = queryUsersByPhone(phone);
                int id = 0;
                if(users==null){
                    Users user = new Users();
                    user.setName(StringRandom.randomName());
                    user.setUsername(StringRandom.randomName());
                    user.setPassword(BCryptUtils.hashPassword(StringRandom.randomName()));
                    user.setCreateTime(LocalDateTime.now());
                    user.setPhone(phone);
                    user.setStatus(1);
                    usersMapper.insert(user);
                    //获取用户id
                    id = user.getId();
                }
                //认证成功--->需要生成保持登录状态的token(jwt)
                //生成token  payload负载,存储数据
                Map<String,Object> payload=new HashMap<>();
                payload.put("phone",phone);
                payload.put("userId",id);
                //设置一个小时
                payload.put("expire_time",System.currentTimeMillis()+1000*60*60);
                String token = JWTUtil.createToken(payload, secret.getBytes(StandardCharsets.UTF_8));
                return token;
            }

        }
        return null;
    }

    @Override
    public Users queryUsersByPhone(String phone) {
        return usersMapper.selectOne(
                new QueryWrapper<Users>()
                        .eq("phone",phone)
        );
    }

}
